/**
 * 深圳金融电子结算中心
 * Copyright (c) 1995-2016 All Rights Reserved.
 */
package com.fesc.trade.demo.util;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fesc.trade.demo.constant.Constants;

/**
 * 返回结果验签工具类，用于对返回字符串的验签
 * @author prd-zzq
 * @version $Id: Response.java, v 0.1 2016年8月30日 下午2:32:49 prd-zzq Exp $
 */
public class ResponseUtil {

    public static Map<String, Object> getResponseMap(String responseStr) {
        JSONObject jsonObject = JSON.parseObject(responseStr);

        Map<String, Object> map = new TreeMap<>();
        Set<String> keySet = jsonObject.keySet();

        for (String key : keySet) {
            map.put(key, jsonObject.get(key));
        }
        return map;
    }

    public static boolean verifySign(String response) {

        JSONObject jsonObject = JSON.parseObject(response);

        Map<String, Object> map = null;
        String sign = null;
        Set<String> keySet = jsonObject.keySet();

        for (String key : keySet) {
            if (key.equals(Constants.SIGN)) {
                sign = jsonObject.getString(key);
            } else {
                map = getResponseMap(jsonObject.getString(key));
            }
        }

        try {
            return SecurityUtil.rsaVerify(JSON.toJSONString(map), Constants.DECODE_PUBLIC_KEY, sign, StandardCharsets.UTF_8.displayName());
        } catch (Exception e) {
            throw new RuntimeException("验签异常", e);
        }
    }
}
